﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace StormCoding.DIExtensions.Selector
{
    public class TypeSelector : ITypeSelector, ISelector
    {
        private IList<ISelector> Selectors { get; } = new List<ISelector>();

        /// <summary>
        /// 从bin文件夹加载所有dll
        /// </summary>
        /// <returns></returns>
        /// <exception cref="AppDomainUnloadedException"></exception>
        public IImplementationTypeSelector FromWebAppAssemblies()
        {
            string binPath = AppContext.BaseDirectory;
            if (string.IsNullOrEmpty(binPath))
            {
                throw new AppDomainUnloadedException();
            }
            var dllFiles = Directory.GetFileSystemEntries(binPath, "*.dll",new EnumerationOptions { 
                IgnoreInaccessible = true,
                MatchCasing = MatchCasing.CaseInsensitive,
                RecurseSubdirectories = false
            });
            foreach(var dllPath in dllFiles)
            {
                try
                {
                    var an = AssemblyName.GetAssemblyName(dllPath);
                    if (!AppDomain.CurrentDomain.GetAssemblies().Any(t => t.GetName().FullName == an.FullName)){
                        AppDomain.CurrentDomain.Load(an);
                    }
                }
                catch (BadImageFormatException ex)
                {
                    Trace.TraceError(ex.ToString());
                }
            }
            Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
            return AddSelector(assemblies.SelectMany(asm => asm.DefinedTypes).Select(x => x.AsType()));
        }
        private IImplementationTypeSelector AddSelector(IEnumerable<Type> types)
        {
            var selector = new ImplementationTypeSelector(this, types);
            Selectors.Add(selector);
            return selector;
        }

        public void Register(IServiceCollection services, RegistrationBehavior behavior)
        {
            foreach (var selector in Selectors)
            {
                selector.Register(services, behavior);
            }
        }
    }
}
